package com.linglingC.controller;

import com.linglingC.pojo.Result;
import com.linglingC.pojo.User;
import com.linglingC.service.UserService;
import com.linglingC.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@CrossOrigin
@RestController
public class UserContrroller {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public Result login(String account,String password){

        log.info("用户登录操作: {} {}",account,password);

        User user =userService.login(account,password);

        if(user==null){
            return Result.error("用户名或密码错误!");
        }else {
            Map<String, Object> claims=new HashMap<>();
            claims.put("account",user.getAccount());
            claims.put("name",user.getName());
            String jwt= JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }

    }

    @PostMapping("/loadImage")
    public Result loadImage(@RequestParam(value="image") MultipartFile image) throws IOException {
        log.info("头像图片上传功能: {}", image.getOriginalFilename());
        userService.uploadImage(image);

        return Result.success();
    }

    @GetMapping("/getUser")
    public Result getUser(HttpServletRequest request){
        String token=request.getHeader("token");
        Claims jwt=  JwtUtils.parseJWT(token);
        User user=userService.getUser(jwt.get("account",String.class));
        return Result.success(user);
    }

    @PutMapping("/updatePassword")
    private Result updatePassword(String password,HttpServletRequest request){
        log.info("修改密码: {}", password);
        userService.updatePassword(password,request);


        return Result.success();
    }

    @PutMapping("/updateName")
    private Result updateName(String name,HttpServletRequest request){
        log.info("修改昵称: {}", name);
        User user=userService.updateName(name,request);

        Map<String, Object> claims=new HashMap<>();
        claims.put("account",user.getAccount());
        claims.put("name",user.getName());
        String jwt= JwtUtils.generateJwt(claims);
        return Result.success(jwt);

    }
}
